import request from '@/ulits/request'
export default {
  state: {
    code: null,
    token: localStorage.getItem('TOKEN'),
    userinfo: {},
  },
  getters: {

  },
  mutations: {
    GETCODE(state, res) {
      state.code = res
    },
    USERLOHIN(state, token) {
      state.token = token
    },
    GETUSERINFO(state, userInfo) {
      state.userinfo = userInfo
    },
    //清除token
    USERLOGOUT(state) {
      state.token = '',
        state.userinfo = {},
        localStorage.removeItem('TOKEN')
    }
  },
  actions: {
    // /user/passport/sendCode/{phone} get请求
    //获取验证码
    async getCode(state, data) {
      let { data: res } = await request.get(`/user/passport/sendCode/${data.phone}`)
      state.commit('GETCODE', res)
    },
    // /user/passport/register  post请求
    //注册账号
    async userRegister(state, data) {
      let { data: res } = await request.post('/user/passport/register', data)
      if (res.code == 200) {
        return 'ok'
      } else {
        return Promise.reject(new Error('失败'))
      }
    },
    // /user/passport/login post请求
    async userLogin(state, data) {
      let res = await request.post('/user/passport/login', data)
      if (res.code == 200) {
        localStorage.setItem('TOKEN', res.data.token)
        return state.commit('USERLOHIN', res.data.token)
      } else {
        return Promise.reject(new Error('失败'))
      }
    },
    // /user/passport/auth/getUserInfo  get请求
    async getUserInfo(state) {
      let res = await request.get('/user/passport/auth/getUserInfo')
      if (res.code == 200) {
        state.commit('GETUSERINFO', res)
      }
    },
    // /user/passport/logout  get请求
    async userLogOut(state) {
      let res = await request.get('/user/passport/logout')
      console.log(res);
      if (res.code == 200) {
        //注意：action里面不能清除state中的token
        state.commit('USERLOGOUT')
        return 'ok'
      } else {
        return Promise.reject(new Error('失败'))
      }
    }

  }
}